//
//  SettingsViewController.m
//  Memento 3.0
//
//  Created by Chris Maddocks on 10-07-31.
//  Copyright 2010 Team Memento. All rights reserved.
//
//  10-08-04: Fix bug with invalid selector in backup (C. Maddocks)
//  10-08-03: Fix bug with first responder preventing interaction with action sheets when keyboard still visible  (C. Maddocks)
//  10-08-03: Fix bugs found in settings synchronization with Settings.app and table view.  (C. Maddocks)
//  10-08-03: Integrate buttons in table view; fix scrolling issues.  Support for deleting current memory.  (C. Maddocks)
//  10-08-03: Force sort after restoring from backup.  Add hooks for progress bar during retrieve, backup.  (C. Maddocks)
//  10-08-01: Integrate ServerController  (C. Maddocks)
//  10-07-31: Initial creation (C. Maddocks)

#import "SettingsViewController.h"
#import "ServerController.h"
#import "PhotoCollection.h"

@implementation SettingsViewController

@synthesize photoCollection, sortMethod, serverURL, serverUsername, serverPassword, textFieldBeingEdited;

- (IBAction)dismiss {
	[self dismissModalViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults synchronize];
	
	NSString *sortMethodString = [NSString stringWithFormat:@"%d", sortMethod];
	[defaults setObject:sortMethodString forKey:kSortKey];
	[defaults setObject:self.serverURL forKey:kServerURLKey];
	[defaults setObject:self.serverUsername forKey:kServerUsernameKey];
	[defaults setObject:self.serverPassword forKey:kServerPasswordKey];
	
	if (oldSortMethod != sortMethod) {
		[self.photoCollection sortBy:sortMethod];
	}	
}

#pragma mark -
#pragma mark Table View Data Source Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 3;
}

- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
	switch (section) {
		case 0: 
			return 2;
		case 1:
			return 3;
		case 2:
			return 0;
		default:
			return 0;
	}
}

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
	switch (section) {
		case 0:
			return @"Sort memories by";
		case 1:
			return @"Server settings";
		case 2:
			return @"Current memory settings";
		default:
			return @"";
	}
}


- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	NSUInteger section = [indexPath section];
	NSUInteger row = [indexPath row];
	
	NSString *cellLabel = @"";
	NSString *cellValue = @"";
	UITableViewCellAccessoryType cellAccessory = UITableViewCellAccessoryNone;

	static NSString *ChecklistCellIdentifier	= @"ChecklistCellIdentifier";	
	static NSString *TextCellIdentifier			= @"TextCellIdentifier";
	
	static NSString *cellIdentifier = @"GenericCellIdentifier";

	
	switch (section) {
		case 0:
			switch (row) {
				case 0:
					cellLabel = @"Recent photos first";
					cellIdentifier = ChecklistCellIdentifier;
					if (sortMethod == kSortByDate) {
						cellAccessory = UITableViewCellAccessoryCheckmark;	
					}
					break;
				case 1:
					cellLabel = @"Nearest photos first";
					cellIdentifier = ChecklistCellIdentifier;
					if (sortMethod == kSortByLocation) {
						cellAccessory = UITableViewCellAccessoryCheckmark;	
					}				
					break;
			}
			break;
			
		case 1:
			switch (row) {
				case kServerURLTag:
					cellLabel = @"Server";
					cellValue = serverURL;
					cellIdentifier = TextCellIdentifier;
					break;
				case kServerUsernameTag:
					cellLabel = @"Username";
					cellValue = serverUsername;
					cellIdentifier = TextCellIdentifier;
					break;
				case kServerPasswordTag:
					cellLabel = @"Password";
					cellValue = serverPassword;
					cellIdentifier = TextCellIdentifier;
					break;
			}
			break;
		case 2:
			//cellLabel = @"Delete";
			break;
	}
	
	UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc]
				initWithStyle:UITableViewCellStyleValue1
				 reuseIdentifier:cellIdentifier] autorelease];
		
		if (cellIdentifier == TextCellIdentifier) {
			UITextField *textField = [[UITextField alloc] initWithFrame: CGRectMake(90, 12, 200, 25)];
			[textField setDelegate:self];
			[textField addTarget:self action:@selector(textFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEndOnExit];
			[cell.contentView addSubview:textField];

			textField.textAlignment = UITextAlignmentRight;
			textField.returnKeyType = UIReturnKeyDone;
			textField.clearsOnBeginEditing = NO;
			textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
			textField.autocorrectionType = UITextAutocorrectionTypeNo;
		}
	}
	
	cell.textLabel.text = cellLabel;
	cell.accessoryType = cellAccessory;
	
	if (cellIdentifier == TextCellIdentifier) {
		UITextField *textField = nil;
		for (UIView *oneView in cell.contentView.subviews) {
			if ([oneView isMemberOfClass:[UITextField class]]) {
				textField = (UITextField *)oneView;
			}
		}
		textField.text = cellValue;
		textField.secureTextEntry = (row == kServerPasswordTag);
		textField.keyboardType = (row == kServerURLTag) ? UIKeyboardTypeURL : UIKeyboardTypeASCIICapable;
		textField.tag = row;
		
		if (textFieldBeingEdited == textField) {
			textFieldBeingEdited = nil;
		}
	} else {
		cell.detailTextLabel.text = cellValue;
	}
	return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
	
	if (section == 1) {
		return 73;
	} else if (section == 2) {
		return 53;
	}
	
	return 0;
	
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
	
    if (section == 1) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
        view.backgroundColor = [UIColor clearColor];
		
		UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
		button.frame = CGRectMake(10, 10, 116, 43);
		[button setTitle:@"Backup" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(backupToServer) forControlEvents:UIControlEventTouchUpInside];
		[view addSubview:button];
		
		button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  	    button.frame = CGRectMake(194, 10, 116, 43);
		[button setTitle:@"Restore" forState:UIControlStateNormal];
		[button addTarget:self action:@selector(retrieveFromServer) forControlEvents:UIControlEventTouchUpInside];
		[view addSubview:button];
				
        return [view autorelease];
    } 
	else if (section == 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
        view.backgroundColor = [UIColor clearColor];
		
		UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
		button.frame = CGRectMake(10, 0, 300, 43);
		[button setTitle:@"Delete current memory" forState:UIControlStateNormal];
		[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
		[button addTarget:self action:@selector(deleteCurrentMemory) forControlEvents:UIControlEventTouchUpInside];

		UIImage *buttonRecordImageNormal = [UIImage imageNamed:@"redButton.png"];
		UIImage *stretchableButtonRecordImageNormal = [buttonRecordImageNormal
													   stretchableImageWithLeftCapWidth:15 topCapHeight: 0];
		[button setBackgroundImage:stretchableButtonRecordImageNormal 
							  forState:UIControlStateNormal];
	
		[view addSubview:button];		
		
        return [view autorelease];
	}
	
    return nil;
}

#pragma mark -
#pragma mark Table View Delegate methods

- (void)tableView:(UITableView *)aTableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	int newSection = [indexPath section];
	int newRow = [indexPath row];
	
	UITableViewCell *newCell = nil;
	UITableViewCell *oldCell = nil;
	
	switch (newSection) {
		case 0:
			newCell = [aTableView cellForRowAtIndexPath:indexPath];
			newCell.accessoryType = UITableViewCellAccessoryCheckmark;
					
			oldCell = [aTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1-newRow inSection:newSection]];
			oldCell.accessoryType = UITableViewCellAccessoryNone;
			
			sortMethod = newRow;
			
			break;
	}
		
	[aTableView deselectRowAtIndexPath:indexPath animated:YES];
	lastIndexPath = indexPath;
}

#pragma mark -
#pragma mark Server UI

- (IBAction)backupToServer {
	ServerController *sc = [[ServerController alloc] initWithURL:[NSURL URLWithString:self.serverURL] usingPhotoCollection:photoCollection delegate:self];
	
	BOOL result = [sc loginWithUsername:self.serverUsername withPassword:self.serverPassword];
	if (!result) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error during restore" 
														message:@"Memento could not log you in.  Please check your username and password and try again.  If you are new to Memento Server, please try a different username."
													   delegate:nil 
											  cancelButtonTitle:@"Okay" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];		
	} else {
		int errors = [sc backupMemories];
		
		if (errors > 0) {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Errors during backup" 
															message:[NSString stringWithFormat:@"%d errors occurred during backup.  Your backup may be incomplete.", errors]
														   delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
			[alert show];
			[alert release];	
		} else {
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Backup completed" 
															message:[NSString stringWithFormat:@"%d memories were added to your backup.", [self.photoCollection count]] 
														   delegate:nil 
												  cancelButtonTitle:@"Okay" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];		
		}
	}

	
	[sc release];
}

- (IBAction)retrieveFromServer {
	// Hide keyboard
	[textFieldBeingEdited resignFirstResponder];	
	
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Replace your memories with server backup?"
															 delegate:self
													cancelButtonTitle:@"Cancel"
											   destructiveButtonTitle:@"Restore"
													otherButtonTitles:nil];
	actionSheet.tag = kActionSheetRestore;
	actionSheet.destructiveButtonIndex = 0;
	[actionSheet showInView:self.view];
	[actionSheet release];
}

- (IBAction)doRetrieveFromServer {
	ServerController *sc = [[ServerController alloc] initWithURL:[NSURL URLWithString:self.serverURL] usingPhotoCollection:photoCollection delegate:self];
	
	BOOL result = [sc loginWithUsername:self.serverUsername withPassword:self.serverPassword];
	if (!result) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error during restore" 
														message:@"Memento could not log you in.\n\nPlease check your username and password and try again.  If you are new to Memento Server, please choose a different username."
													   delegate:nil 
											  cancelButtonTitle:@"Okay" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];		
	} else {
		[sc retrieveMemories];
		[photoCollection sortBy:self.sortMethod];
		
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Restore completed" 
														message:[NSString stringWithFormat:@"%d memories were added to your collection.", [self.photoCollection count]] 
													   delegate:nil 
											  cancelButtonTitle:@"Okay" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
	[sc release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet
didDismissWithButtonIndex: (NSInteger)buttonIndex
{
	if (buttonIndex == [actionSheet cancelButtonIndex]) {
		return;
	}
		
	if (actionSheet.tag == kActionSheetRestore) {
		[self doRetrieveFromServer];
	} else if (actionSheet.tag == kActionSheetDelete) {
		[photoCollection deleteCurrentMemory];
	}
}

- (void)deleteCurrentMemory {
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Really delete current memory?"
															 delegate:self
													cancelButtonTitle:@"Cancel"
											   destructiveButtonTitle:@"Delete"
													otherButtonTitles:nil];
	actionSheet.tag = kActionSheetDelete;
	actionSheet.destructiveButtonIndex = 0;
	[actionSheet showInView:self.view];
	[actionSheet release];
}


#pragma mark -
#pragma mark Delegate notifications for progress bar

- (void)progressChanged:(int)value ofMaximum:(int)maxValue {
	progressView.progress = (float)value/maxValue;
}

#pragma mark -
#pragma mark Notifications

- (void)keyboardWillShow:(NSNotification *)aNotification  {
	CGRect keyboardBounds;
	
	NSDictionary *userInfo = [aNotification userInfo];
	NSValue *keyboardBoundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
	[keyboardBoundsValue getValue:&keyboardBounds];
	
	CGRect frame = self.view.frame;
	frame.size.height = frame.size.height - keyboardBounds.size.height;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:0.3f];
	self.view.frame = frame;
	[UIView commitAnimations];
	NSLog (@"%@", [tableView indexPathForSelectedRow]);
}

- (void)keyboardWillHide:(NSNotification *)aNotification  {
	CGRect keyboardBounds;
	
	NSDictionary *userInfo = [aNotification userInfo];
	NSValue *keyboardBoundsValue = [userInfo objectForKey:UIKeyboardBoundsUserInfoKey];
	[keyboardBoundsValue getValue:&keyboardBounds];
	
	CGRect frame = self.view.frame;
	frame.size.height = frame.size.height + keyboardBounds.size.height;

	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:0.3f];
	self.view.frame = frame;
	[UIView commitAnimations];
	
}

- (void) textFieldDidBeginEditing:(UITextField *)textField {
    UITableViewCell *cell = (UITableViewCell*) [[textField superview] superview];
    [tableView scrollToRowAtIndexPath:[tableView indexPathForCell:cell] atScrollPosition:UITableViewScrollPositionTop animated:YES];
	
	textFieldBeingEdited = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	switch (textField.tag) {
		case kServerURLTag:
			self.serverURL = textField.text;
			break;
		case kServerUsernameTag:
			self.serverUsername = textField.text;
			break;
		case kServerPasswordTag:
			self.serverPassword = textField.text;
			break;
	}
	
	[textFieldBeingEdited resignFirstResponder];
	textFieldBeingEdited = nil;
}


#pragma mark -
#pragma mark Initialization and cleanup
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

- (id)initWithPhotoCollection:(PhotoCollection *)aPhotoCollection {
	self.photoCollection = aPhotoCollection;
	return [super init];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];	
	
	
	// Observe keyboard hide and show notifications to resize the text view appropriately.
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];	
}

- (void)refreshSettings {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults synchronize];

	NSString *sortMethodStr = [defaults objectForKey:kSortKey];
    sortMethod = [sortMethodStr intValue];
	self.serverURL = [defaults objectForKey:kServerURLKey];
	self.serverUsername = [defaults objectForKey:kServerUsernameKey];
	self.serverPassword = [defaults objectForKey:kServerPasswordKey];
	
	if ([self.serverURL isEqualToString:@""]) {
		self.serverURL = @"http://memento.freehostingcloud.com/";
	}
	
	oldSortMethod = sortMethod;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	[serverURL release];
	[serverUsername release];
	[serverPassword release];
	 
    [super viewDidUnload];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
	[self refreshSettings];
	[tableView reloadData];
}


- (void)dealloc {
    [super dealloc];
}


@end
